//
//  LQUserAccountViewModel.swift
//  Weibo
//
//  Created by ios on 16/8/10.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

class LQUserAccountViewModel: NSObject {
    static let shareUserAccount:LQUserAccountViewModel = LQUserAccountViewModel()
    //用户账号模型
    var userAccount: LQUserAccount?{
    return LQUserAccount.loadUserAccount()
    }
    
    //判断是否登录
    var isLogin:Bool{
        
        return accessToken != nil
        
    }

    //  封装accesstoken,判断逻辑
    var accessToken: String?{
    //判断accessToken是否为空
        guard let token = userAccount?.access_token else{
        return nil
        }
        //如果accessToken不为nil 判断时间是否过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        //  如果是降序表示accesstoken没有过期
        if result == NSComparisonResult.OrderedDescending {
           return token
        }else{
        return nil
        }
    }
    
          //  通过code获取accesstoken
    func reqeustAccessTokenWithCode(code: String,callBack:(isSuccess:Bool) -> ()){
        LQAFNetworkingTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
            if error != nil {
                print("网络请求失败")
                callBack(isSuccess: false)
                return
            }
          //  判断服务端给的数据是否是一个正确的字典
            guard let dic = response as? [String: AnyObject] else{
              print("不是一个正确的字典格式")
              callBack(isSuccess: false)
              return
            }
            //  代码执行到此,字典没有问题
            let userAccount = LQUserAccount(dic: dic)
            print(userAccount.access_token)
            self.requestUserInfo(userAccount,callBack: callBack)
        }
    }
    
        //  通过accesstoken和uid获取用户信息
        func requestUserInfo(userAccount:LQUserAccount,callBack:(isSuccess:Bool) -> ()){
        LQAFNetworkingTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                print("网络请求失败")
                callBack(isSuccess: false)
                return
            }
            guard let dic = response as? [String: AnyObject] else{
                print("不是一个正确的字典格式")
                callBack(isSuccess: false)
                return
            }
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //保存用户信息
            userAccount.saveUserAccount()
            callBack(isSuccess: true)
            }
        
        }

}
